package com.opengms.HydroModelsIntegration.Controller;

import org.apache.commons.io.FileUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;

/**
 * @Author: David.Xiao
 * @Date: 2018/12/7 16:29
 * @Description:GET方法接收前台请求，并返回；访问给定URL的Web Service
 */
@WebServlet(name = "TestGet",urlPatterns = "/TestGet")
public class TestGet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置对客户端请求进行重新编码的编码
        req.setCharacterEncoding("utf-8");
        //使客户端浏览器，区分不同种类的数据，并根据不同的MIME调用浏览器内不同的程序嵌入模块来处理相应的数据。
        resp.setContentType("text/html;charset=UTF-8;pageEncoding=UTF-8");
        //指定对服务器响应进行重新编码的编码
        resp.setCharacterEncoding("UTF-8");

        //**********访问Web Service*********//
        String result="";
        String urlName ="http://120.25.83.97:8080/Chinaquery/CalculatePM25China?lat=32&lng=101";
        URL url = new URL(urlName);
//        FileUtils.copyURLToFile(url,new File());

        URLConnection connection = url.openConnection();
        connection.setRequestProperty("accept","*/*");
        connection.setRequestProperty("connection","Keep-Alive");
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
            String line;
            while ((line=in.readLine())!= null)
            {
                result += "\n" + line;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(result);

        String name = req.getParameter("name");
        String time = req.getParameter("time");

        String personJSON = "{\"name" + "\":\"" + name + "\"," + "\"age"
                + "\":" + time + "}";
        System.out.println(personJSON);

        PrintWriter writer=resp.getWriter();
        writer.print(personJSON);
        writer.flush();
        writer.close();
    }
}
